package com.ifgi.sitcom.campusmapperNDrawer.fragments;




import java.io.ByteArrayOutputStream;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.SherlockFragment;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;
import com.ifgi.sitcom.campusmapperNDrawer.R;
import com.ifgi.sitcom.campusmapperNDrawer.activities.MainActivity;
import com.ifgi.sitcom.campusmapperNDrawer.controllers.*;
import com.ifgi.sitcom.campusmapperNDrawer.dialogs.*;
import com.ifgi.sitcom.campusmapperNDrawer.dialogs.ExistingPlanDialog.ExistingPlanDialogListener;
import com.ifgi.sitcom.campusmapperNDrawer.indoordata.*;
import com.ifgi.sitcom.campusmapperNDrawer.io.*;
import com.ifgi.sitcom.campusmapperNDrawer.outdoordata.*;

import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.support.v4.content.CursorLoader;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.Toast;

/*
 * Provides one button to access any existing camera app to be used for capturing 
 * the floorplan image. Provides another button to access any existing gallery app 
 * to select an already existing floorplan image. After image was selected/ created, 
 * Cropping Activity is called.
 */
public class ImageSourceFragment extends SherlockFragment {
	
	public final static String EXTRA_SOURCE_URI = "de.ifgi.sitcom.campusmapper.sourceURI";
	public final static String EXTRA_CROPPED_URI = "de.ifgi.sitcom.campusmapper.croppedURI";

	
	private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100;
	private static final int ACCESS_GALLERY_ACTIVITY_REQUEST_CODE = 200;

	private String mBuildingName;
	private String mBuildingURI;
	private String mFloorNumber;
	
	private RadioButton mRadioButtonCamera;

	
	
	@Override
	public void onCreate (Bundle savedInstanceState){
	    super.onCreate(savedInstanceState);
	    setHasOptionsMenu(true);
	}
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
	{
		View rootView = inflater.inflate(R.layout.activity_choose_image_source, container, false);
		getActivity().setTitle(R.string.title_activity_image_source);
		// get bundle
		Bundle b=getArguments();
		mBuildingName=b.getString(ChooseLocationFragment.EXTRA_BUILDING_NAME);
		mBuildingURI=b.getString(ChooseLocationFragment.EXTRA_BUILDING_URI);
		mFloorNumber=b.getString(ChooseLocationFragment.EXTRA_FLOOR_NUMBER);
		
		mRadioButtonCamera = (RadioButton) rootView.findViewById(R.id.radio_camera);
		
		return rootView;
	}

	/** Called when the user clicks the Camera button */
	public void showCamera(View view) {
		
		// call camera app and take photo, afterwards onActivityResult is called
		Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
	 	cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, getOutputMediaFileUri()); // set the image file name			
	 	startActivityForResult(cameraIntent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);  

	}
	
	/** Create a file Uri for saving an image or video */
	private Uri getOutputMediaFileUri(){
	      return Uri.fromFile(getOutputMediaFile());
	}
	
	/** Create a File for saving an image or video */
	private File getOutputMediaFile(){

	    File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
	              Environment.DIRECTORY_PICTURES), "Floor Plans");

	    // Create the storage directory if it does not exist
	    if (! mediaStorageDir.exists()){
	        if (! mediaStorageDir.mkdirs()){
	            Log.v("debug", "failed to create directory");
	            return null;
	        }
	    }

	    // Create a media file name
	    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.GERMANY).format(new Date());
	    File mediaFile;
        mediaFile = new File(mediaStorageDir.getPath() + File.separator + "IMG_"+ timeStamp + ".jpg");
	    ((MainActivity) getActivity()).setmImageUri( mediaStorageDir.getPath() + File.separator + "IMG_"+ timeStamp + ".jpg");
        Log.v("image uri after get output file", ((MainActivity) getActivity()).getmImageUri());
        
	    return mediaFile;
	}
	
	/** Called when the user clicks the Gallery button */
	public void showGallery(View view) {
		
		Intent photoPickerIntent = new Intent(Intent.ACTION_GET_CONTENT);
		photoPickerIntent.setType("image/*");
		startActivityForResult(photoPickerIntent, ACCESS_GALLERY_ACTIVITY_REQUEST_CODE);
		
	}

	@Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
		
		super.onActivityResult(requestCode, resultCode, data);
		Log.v("debug", "Request Code is " + requestCode);
	    if (resultCode == Activity.RESULT_OK){

	    	
	    	switch (requestCode) {
	    	
	    	case ACCESS_GALLERY_ACTIVITY_REQUEST_CODE:
	    		Uri galleryImageUri = data.getData();
	    		((MainActivity) getActivity()).setmImageUri(getRealPathFromURI(galleryImageUri));
	    		
		        break;
		    	
	    	case CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE:
	    		
	    		break;
	    	
	    	}   	
			
			// start buildingInformationActivity
			launchTransformationActivity();
	    	
	    } else {
	    	Toast.makeText(getActivity(), "no image chosen", Toast.LENGTH_SHORT).show();
	    }
	}
	
	// TODO may throw out of bounds on old android
		public String getRealPathFromURI(Uri contentUri) {
			String[] proj = { MediaStore.Images.Media.DATA };
			//Cursor cursor = getActivity().managedQuery(contentUri, proj, null, null, null);
			
			CursorLoader cursorLoader = new CursorLoader(
			        getActivity(), 
			        contentUri, proj,
			        null, 
			        null, 
			        null);

			Cursor cursor = cursorLoader.loadInBackground();
			
			int column_index = cursor
					.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
			cursor.moveToFirst();
			return cursor.getString(column_index);
		}
	
	
	public void launchTransformationActivity() {
			
		CroppingFragment fragment = new CroppingFragment();
		Bundle b=new Bundle();
		b.putString(ChooseLocationFragment.EXTRA_BUILDING_NAME, mBuildingName);
		b.putString(ChooseLocationFragment.EXTRA_BUILDING_URI, mBuildingURI);
		b.putString(ChooseLocationFragment.EXTRA_FLOOR_NUMBER, mFloorNumber);
		b.putString(EXTRA_SOURCE_URI, ((MainActivity) getActivity()).getmImageUri().toString());
		fragment.setArguments(b);
		
		android.support.v4.app.FragmentTransaction ft = getActivity().getSupportFragmentManager().beginTransaction();
        ft.replace(R.id.content_frame, fragment);
   	    ft.addToBackStack(null);
    	ft.commit();
	}
	

	
	@Override
	public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
		// TODO Auto-generated method stub
		super.onCreateOptionsMenu(menu, inflater);
		inflater.inflate(R.menu.image_source, menu);
		
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		 // handle item selection
		   switch (item.getItemId()) {
		   
		   case R.id.action_next:
				// if camera radio button is checked, call camera
				if(mRadioButtonCamera.isChecked()) showCamera(null);
				// otherwise gallery
				else showGallery(null);
				return true;
		
		      default:
		    	 return super.onOptionsItemSelected(item);		
		   }
		}

}
